<?php


namespace sm_shop\api;
use sm_shop\controller;
use sm_shop\model\cashLogModel;
use sm_shop\model\customerModel;

class balance extends controller{

    /**
     * 获取用户余额（使用微擎系统中的数据）
     */
    public function index(){
        $res = [
            'status'=>0
        ];
        $res['credit'] = customerModel::credit();

        echo json_encode( $res );
    }

    /**
     * 用户余额, 获取记录
     */
    public function record(){

        global $_W;
//        $customer_id = $_W['customer']['id'];
        $w7_uid = $_W['customer']['w7_uid'];

        $condition = [
            'uniacid'   => $_W['uniacid'],
            'uid'       => $w7_uid,
        ];
        $orderBy = 'createtime desc';
        $records = pdo_getall('mc_credits_record', $condition, [], '', $orderBy );

        foreach( $records as &$item ){
            $item['created_at'] = date('Y-m-d H:i', $item['createtime'] );
        }
        echo json_encode( $records );
    }

    /**
     * 用户余额,提现记录
     */
    public function cash_log(){

        global $_W;
        $customer_id = $_W['customer']['id'];
        $log = cashLogModel::log( $customer_id );
        foreach( $log as &$item ){
            $item['status_text'] = cashLogModel::$status_text[ $item['status'] ];
        }
        echo json_encode( $log );
    }

    /**
     * 用户余额,提现申请
     * 每日只能申请一次
     */
    public function cashout(){

        global $_W, $_GPC;
        $res = [
            'status'=> 0
        ];
        $customer_id = $_W['customer']['id'];

        // todo 检查今天是否申请过提现
        $today_log = cashLogModel::todayLog($customer_id);

        if( $today_log ){
            $res['status'] = 1;
            $res['description'] = '今天已经申请过提现，无法再次申请';
            echo json_encode( $res );
            die();
        }

        if( $_GPC['__input']){
            $data = $_GPC['__input'];
        }else{
            $data = $_POST;
        }

        if( !is_numeric($data['amount'] ) || floatval($data['amount']) <= 0 ){

            $res['status'] = 1;
            $res['description'] = '请填写正确的金额';
            echo json_encode( $res );
            die();
        }
        $insertData = [
            'uniacid'=>$_W['uniacid'],
            'customer_id'=>$customer_id,
            'amount'=>$data['amount'],
            'status'=>1,
        ];
        $res['ret'] = sm_pdo_insert('cash_log', $insertData );

        echo json_encode( $res );
    }

}